import React from 'react';
import { Icon } from 'antd';

import { mapValuesDeep } from '@/app/utils/helper';
import _ from 'lodash';

import DatePicker from 'athena-lib/es/DatePicker';
import Slider from 'athena-lib/es/Slider';
import TreeSelect from 'athena-lib/es/TreeSelect';
import Cascader from 'athena-lib/es/Cascader'
import Checkbox from 'athena-lib/es/Checkbox'
import Upload from 'athena-lib/es/Upload'
import Switch from 'athena-lib/es/Switch'
import List from 'athena-lib/es/List'
import Input from 'athena-lib/es/Input';
import InputNumber from 'athena-lib/es/InputNumber';
import TextArea from 'athena-lib/es/TextArea';
import Select from 'athena-lib/es/Select';
import Table from 'athena-lib/es/Table';
import Radio from 'athena-lib/es/Radio';
import FlowImage from 'athena-lib/es/FlowImage';


import AutoCompleteInput from 'athena-lib/es/AutoComplete/AutoCompleteInput';
import AutoCompleteTextarea from 'athena-lib/es/AutoComplete/AutoCompleteTextarea';

import ColorPicker from 'athena-lib/es/ColorPicker';

// import AceEditor from '@/app/components/AceEditor';
// import IconList from '@/app/components/IconList';
// import TimePicker from 'athena-lib/es/TimePicker';

const formFieldComponentRegstry = {
    'icon' : props => {
        return <Icon {...props} />;
    },
    // 'time-picker' : {
    //     render: props => {
    //         return (
    //             <TimePicker {...props}/>
    //         )
    //     }
    // },
    'color-picker' : {
        render: (props) => {
            return (
                <ColorPicker 
                    {...props}
                />
            )
        }
    },
    'input' : {
        propsDesc: Input.propsDesc,
        render: (props, renderFormItem) => {
            return (
                <Input
                    {...props} 
                    renderFormItem={renderFormItem} 
                    renderField={renderField} 
                />
            )
        }
    },
    // 'ace-editor' : {
    //     propsDesc: AceEditor.propsDesc,
    //     render: (props, renderFormItem) => {
    //         return (
    //             <AceEditor
    //                 { ...props }
    //                 renderFormItem={renderFormItem}
    //                 renderField={renderField}
    //             />
    //         );
    //     }
    // },
    'textarea' : {
        propsDesc: TextArea.propsDesc,
        render: props => {
            return (
                <TextArea
                    { ...props }
                    renderField={renderField}
                />
            );
        }
    },
    'select' : {
        propsDesc: Select.propsDesc,
        render: (props) => {
            return (
                <Select { ...props } />
            );
        }
    },
    'radio' : {
        propsDesc: Radio.propsDesc,
        render: props => {
            return (
                <Radio {...props} />
            );
        }
    },
    'input-number' : {
        propsDesc: InputNumber.propsDesc,
        render: (props) => {
            return (
                <InputNumber {...props} />
            )
        }
    },
    'switch' : {
        valuePropName: 'checked',
        propsDesc: Switch.propsDesc,
        render: props => {
            return (
                <Switch {...props} />
            )
        }
    },
    'table' : {
        propsDesc: Table.propsDesc,
        render: props => {
            return (
                <Table
                    {...props}
                    renderField={renderField}
                />
            )
        }
    },
    'date-picker': {
        propsDesc: DatePicker.PropsDesc,
        render: props => {
            return (
                <DatePicker { ...props } />
            )
        }
    },
    'slider': {
        propsDesc: Slider.PropsDesc,
        render: props => {
            return (
                <Slider {...props} />
            )
        }
    },
    'tree-select': {
        propsDesc: TreeSelect.PropsDesc,
        render: props => {
            return (
                <TreeSelect {...props} />
            )
        }
    },
    'cascader': {
        propsDesc: Cascader.propsDesc,
        render: props => {
            return (
                <Cascader {...props} />
            )
        }
    },
    'checkbox': {
        propsDesc: Checkbox.propsDesc,
        render: props => {
            return (
                <Checkbox {...props} />
            )
        }
    },
    'upload': {
        propsDesc: Upload.propsDesc,
        render: props => {
            return (
                <Upload {...props} />
            )
        }
    },
    'list': {
        propsDesc: List.propsDesc,
        render: props => {
            return (
                <List {...props} />
            )
        }
    },
    'flow-image': {
        propsDesc: FlowImage.propsDesc,
        render: props => {
            return (
                <FlowImage {...props} />
            )
        }
    },
    'autoCompleteInput' : {
        render: props => {
            return (
                <AutoCompleteInput 
                    {...props}
                    renderField={renderField}
                />
            )
        }
    },
    'autoCompleteTextarea' : {
         render: props => {
             return (
                 <AutoCompleteTextarea 
                    {...props}
                 />
             )
         }
    },
    // 'icon-list' : {
    //     render: props => {
    //         return (
    //             <IconList 
    //                 {...props}
    //             />
    //         )
    //     }   
    // }
}

/**
 * 根据Field模型渲染表单项组件
 */
export const renderField = ({ 
    form,
    field, //Field模型
    size, //控件大小，用于覆盖模型配置
    layoutType, //表单布局类型
    onClick,//点击事件
    onAddonAfterClick, //标签后缀点击事件
    onValueChange=()=>{},//值改变回调
    onBlur,//失去焦点
    setFieldValue,
    getFieldValue,
    value,
    renderFormItem=({component})=>{return component} } //回调函数，当控件实现者声明了这个参数，则传递给他，让他可自主控制渲染FormItem的时机
) => {
    if (typeof getFieldValue !== 'function') {
        getFieldValue = () => 
            form && form.getFieldValue(field.name);
    }
    if (typeof getFieldValue !== 'function') {
        setFieldValue = value => 
            form && form.setFieldsValue({[field.name]:value});
    }

    const { uiComponent={}, placeholder, defaultValue, dataType='string',style:styleFromField={} } = field;
    const { type, props, auth } = uiComponent;
    const FieldComponent = formFieldComponentRegstry[type];
    let uiProps = props || {};
    if (typeof uiProps === 'string') {
        try { uiProps = JSON.parse(uiProps); } catch (e) {/*ignore*/}
    }
    if(typeof auth != 'undefined' && Object.keys(auth).length > 0){
        if(!auth.editable){
            uiProps.disabled = true;
        }
    }
    uiProps = mapValuesDeep(uiProps, (opts) => {
        try { return JSON.parse(opts.value); } catch (e) {/*ignore*/}
    });
    const { style:styleFromProps={} } = uiProps;
    const style = _.defaultsDeep({}, styleFromProps, styleFromField);

    value = value || getFieldValue();
    if (dataType === 'object') {
        if (typeof value === 'string') {
            try { value = JSON.parse(value); } catch (e) {/*ignore*/}
        }
        if (typeof value === 'object') {
            value = mapValuesDeep(value, (opts) => {
                try { return JSON.parse(opts.value); } catch (e) {/*ignore*/}
            });
        }
    }

    const newProps = {
        placeholder,
        onClick,
        onAddonAfterClick, 
        layoutType,
        getFieldValue,
        setFieldValue,
        onValueChange,
        onBlur,
        value,
        ...uiProps,
        style
    };
    if (size) {
        newProps.size = size;
    }
    
    const { onChange=()=>{} } = newProps;
    newProps.onChange = (e) => {
        if (typeof e !== 'undefined' && e != null) {
            const newValue = e.target ? e.target.value : e;
            onValueChange && onValueChange(newValue);
        }
        if (typeof onChange === 'function') {
            onChange(e);
        }
    };
    

    let formItem;
    if (FieldComponent) {
        if (typeof FieldComponent === 'object') {
            const argsLength = FieldComponent.render.prototype.constructor.length;
            if (argsLength === 1) {
                let valuePropName;
                if (FieldComponent.valuePropName) {
                    valuePropName = FieldComponent.valuePropName;
                    newProps[valuePropName] = defaultValue;
                    delete newProps['value'];
                }
                const component = FieldComponent.render(newProps);
                formItem = renderFormItem({component, valuePropName});
            } else {
                formItem = FieldComponent.render(newProps, renderFormItem);
            }
        } else {
            const argsLength = FieldComponent.prototype.constructor.length;
            if (argsLength === 1) {
                const component = FieldComponent(newProps);
                formItem = renderFormItem({ component });
            } else {
                formItem = FieldComponent(newProps, renderFormItem);
            }
        }
    }
    return formItem;
}

export default formFieldComponentRegstry;